package vip.web3.admin.sys.service.impl.biz;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import vip.web3.admin.common.utils.Query;
import vip.web3.admin.sys.dao.biz.AOrderDao;
import vip.web3.admin.sys.entity.biz.AOrderEntity;
import vip.web3.admin.sys.entity.biz.AUserEntity;
import vip.web3.admin.sys.entity.biz.AUserWalletEntity;
import vip.web3.admin.sys.form.user.OrderPageForm;
import vip.web3.admin.sys.mapper.AOrderMapper;
import vip.web3.admin.sys.service.biz.IAOrderService;
import vip.web3.admin.sys.service.biz.IARecordService;
import vip.web3.admin.sys.service.biz.IAUserService;
import vip.web3.admin.sys.service.biz.IAUserWalletService;
import vip.web3.admin.sys.service.sys.SysConfigService;
import vip.web3.admin.sys.vo.biz.OrderVo;
import vip.web3.admin.sys.vo.biz.export.ExOrderVo;
import vip.web3.common.enums.AssetEnum;
import vip.web3.common.enums.OperateEnum;
import vip.web3.common.utils.Convert;
import vip.web3.common.utils.PageUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


/**
 * 订单Service业务层处理
 *
 * aut-horlilei
 * @date 2024-09-27
 */
@Service
public class AOrderServiceImpl extends ServiceImpl<AOrderDao, AOrderEntity> implements IAOrderService {

    @Resource
    private SysConfigService sysConfigService;

    @Resource
    private IAUserService iAUserService;

    @Resource
    private IAUserWalletService iAUserWalletService;

    @Resource
    private IARecordService iARecordService;

    /**
     * 批量删除订单
     *
     * @param ids 需要删除的订单主键
     * @return 结果
     */
    @Override
    public int deleteAOrderByIds(String ids) {
        return this.baseMapper.deleteAOrderByIds(Convert.toIntArray(ids));
    }

    @Override
    public void baseReward() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        QueryWrapper<AOrderEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("active", 1).and(wrapper -> wrapper.isNull("send_date").or().ne("send_date", LocalDate.now().format(formatter)));
        List<AOrderEntity> orders = baseMapper.selectList(queryWrapper);
        if(!CollectionUtils.isEmpty(orders)){
            for (AOrderEntity order : orders) {
                try {

                    // 获取订单创建时间的时间戳
                    long createTime = order.getCreateDate().getTime();
                    // 获取当前时间的时间戳
                    long currentTime = System.currentTimeMillis();
                    // 计算两个时间的差值（以毫秒为单位）
                    long timeDifference = currentTime - createTime;
                    // 将毫秒转换为小时
                    long hoursDifference = timeDifference / (1000 * 60 * 60);

                    if(order.getSendDate()!=null && !order.getSendDate().isEmpty()){
                        // 1. 将字符串转换为 Date 对象
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        try {
                            Date sendDate = dateFormat.parse(order.getSendDate());  // 转换字符串为 Date
                            // 2. 获取当前时间
                            Date currentDate = new Date();
                            // 3. 计算两个时间的差值（以毫秒为单位）
                            long timeDifferenceInMillis = currentDate.getTime() - sendDate.getTime();
                            // 4. 将毫秒差转换为小时差
                            hoursDifference = TimeUnit.MILLISECONDS.toHours(timeDifferenceInMillis);
//                            hoursDifference = new Date().getTime()- order.getSendDate()
                            log.error("相差的小时数: " + hoursDifference);
                        } catch (ParseException e) {
                            e.printStackTrace();  // 处理字符串解析异常
                        }

                    }

                    if( hoursDifference < 24 || order.getCreateDate().getTime()*180 - new Date().getTime() < 24 * 60 * 60 * 1000L ){
                        continue;
                    }
                    BigDecimal releaseAmount = order.getIncome();
                    Integer releaseDay = order.getTotalTimes();
                    Integer releaseLeft = order.getLeftTimes();
                    BigDecimal releasing = order.getTotalIncome();
                    BigDecimal released = order.getLeftIncome();
                    order.setTotalTimes(releaseDay + 1);
                    order.setLeftTimes(releaseLeft - 1);
                    order.setTotalIncome(releasing.add(releaseAmount));
                    order.setLeftIncome(released.subtract(releaseAmount));

                    SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
                    String timePart = timeFormat.format(order.getCreateDate());
                    order.setSendDate(LocalDate.now().format(formatter)+" "+timePart);

                    if(releaseLeft.intValue() == 1){
                        // 最后一天, 释放完毕后, 出局
                        order.setActive(AssetEnum.STATUS0.getCode());
                    }
                    baseMapper.updateById(order);

                    AUserWalletEntity wallet = iAUserWalletService.findByUserId(order.getUserId());
                    // 处理余额
                    String desc = ": CNY";
                    if(order.getType().intValue() == 1){
                        iAUserWalletService.updateWallet(wallet, AssetEnum.TYPE3.getCode(), releaseAmount, BigDecimal.ZERO);
                    } else{
                        iAUserWalletService.updateWallet(wallet, AssetEnum.TYPE4.getCode(), releaseAmount, BigDecimal.ZERO);
                        desc = ": USDT";
                    }
                    // 添加记录
                    iARecordService.addRewardRecord(order.getUserId(),
                            order.getMobile(),
                            OperateEnum.TYPE5.getType(),
                            OperateEnum.TYPE5.getMark(),
                            OperateEnum.TYPE5.getDesc() + desc,
                            releaseAmount,
                            BigDecimal.ZERO,
                            null,
                            "",1
                    );
                }catch (Exception ex){
                    log.error("静态释放异常...");
                }
            }
        }
    }

    @Override
    public void inviteReward() {
        QueryWrapper<AOrderEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0);
        queryWrapper.ne("pro_id", 1);
        List<AOrderEntity> ens = baseMapper.selectList(queryWrapper);
        if(!CollectionUtils.isEmpty(ens)){
            // 系统参数需配置
            String path1Rate_ = sysConfigService.getValue("alloy:invite:reward:1");
            BigDecimal path1Rate = new BigDecimal(path1Rate_);
            String path2Rate_ = sysConfigService.getValue("alloy:invite:reward:2");
            BigDecimal path2Rate = new BigDecimal(path2Rate_);
            String path3Rate_ = sysConfigService.getValue("alloy:invite:reward:3");
            BigDecimal path3Rate = new BigDecimal(path3Rate_);
            for (AOrderEntity entity : ens) {
                BigDecimal amountCny = entity.getAmountCny();
                BigDecimal path1Amount = amountCny.multiply(path1Rate);
                BigDecimal path2Amount = amountCny.multiply(path2Rate);
                BigDecimal path3Amount = amountCny.multiply(path3Rate);
                try {
                    AUserEntity user = iAUserService.getById(entity.getUserId());
                    AUserEntity path1 = iAUserService.getById(user.getPath());
                    if(path1 != null && path1Amount.compareTo(BigDecimal.ZERO) > 0){
                        if(path1.getActive().intValue() != 10){
                            // 操作钱包
                            AUserWalletEntity path1Wallet = iAUserWalletService.findByUserId(path1.getId());
                            iAUserWalletService.updateWallet(path1Wallet, AssetEnum.TYPE3.getCode(), path1Amount, BigDecimal.ZERO);
                            // 添加记录
                            iARecordService.addRewardRecord(path1.getId(),
                                    path1.getMobile(),
                                    OperateEnum.TYPE6.getType(),
                                    OperateEnum.TYPE6.getMark(),
                                    OperateEnum.TYPE6.getDesc(),
                                    path1Amount,
                                    BigDecimal.ZERO,
                                    OperateEnum.OPERATE_TYPE1.getType(),
                                    "",AssetEnum.STATUS1.getCode()
                            );
                        }

                        AUserEntity path2 = iAUserService.getById(path1.getPath());
                        if(path2 != null && path2Amount.compareTo(BigDecimal.ZERO) > 0){
                            if(path2.getActive().intValue() != 10){
                                // 操作钱包
                                AUserWalletEntity path2Wallet = iAUserWalletService.findByUserId(path2.getId());
                                iAUserWalletService.updateWallet(path2Wallet, AssetEnum.TYPE3.getCode(), path2Amount, BigDecimal.ZERO);
                                // 添加记录
                                iARecordService.addRewardRecord(path2.getId(),
                                        path2.getMobile(),
                                        OperateEnum.TYPE6.getType(),
                                        OperateEnum.TYPE6.getMark(),
                                        OperateEnum.TYPE6.getDesc(),
                                        path2Amount,
                                        BigDecimal.ZERO,
                                        OperateEnum.OPERATE_TYPE1.getType(),
                                        "",1
                                );
                            }

                            AUserEntity path3 = iAUserService.getById(path2.getPath());
                            if(path3 != null && path3Amount.compareTo(BigDecimal.ZERO) > 0){
                                if(path3.getActive().intValue() != 10){
                                    // 操作钱包
                                    AUserWalletEntity path3Wallet = iAUserWalletService.findByUserId(path3.getId());
                                    iAUserWalletService.updateWallet(path3Wallet, AssetEnum.TYPE3.getCode(), path3Amount, BigDecimal.ZERO);
                                    // 添加记录
                                    iARecordService.addRewardRecord(path3.getId(),
                                            path3.getMobile(),
                                            OperateEnum.TYPE6.getType(),
                                            OperateEnum.TYPE6.getMark(),
                                            OperateEnum.TYPE6.getDesc(),
                                            path3Amount,
                                            BigDecimal.ZERO,
                                            OperateEnum.OPERATE_TYPE1.getType(),
                                            "",1
                                    );
                                }
                            }
                        }
                    }
                } catch (Exception ex){
                    log.error("推荐奖励释放异常...");
                }
                baseMapper.initStatus();
            }
        }
    }

    @Override
    public PageUtils pageOrders(Map<String, Object> params, OrderPageForm form) {
        IPage<AOrderEntity> page = this.page(
                new Query<AOrderEntity>().getPage(params),
                this.listOrders(form).getWrapper()
        );
        List<AOrderEntity> records = page.getRecords();
        List<OrderVo> adminOrderVoList = AOrderMapper.INSTANCE.toAdminOrderVoList(records);

        return new PageUtils(adminOrderVoList, page);
    }

    private LambdaQueryChainWrapper<AOrderEntity> listOrders(OrderPageForm form) {
        return this.lambdaQuery()
                .ge(Objects.nonNull(form.getStartTime()), AOrderEntity::getCreateDate, form.getStartTime())
                .le(Objects.nonNull(form.getEndTime()), AOrderEntity::getCreateDate, form.getEndTime())
                .eq(Objects.nonNull(form.getType()), AOrderEntity::getType, form.getType())
                .eq(Objects.nonNull(form.getStatus()), AOrderEntity::getActive, form.getStatus())
                .like(StringUtils.isNotBlank(form.getProName()), AOrderEntity::getProName, form.getProName())
                .and(StringUtils.isNotBlank(form.getKeyWord()),
                        wrapper -> wrapper.like(AOrderEntity::getMobile, form.getKeyWord())
                                .or()
                                .like(AOrderEntity::getUserId, form.getKeyWord())
                );
    }

    @Override
    public List<ExOrderVo> export(Map<String, Object> params, OrderPageForm form) {
        List<AOrderEntity> list = this.listOrders(form).list();
        List<OrderVo> adminOrderVoList = AOrderMapper.INSTANCE.toAdminOrderVoList(list);
        return AOrderMapper.INSTANCE.toExOrderVoList(adminOrderVoList);
    }
}
